<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete, Folder } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from "element-plus"
import { getPageCategories, addCategory, updateCategory, deleteCategory } from '@/api/admin'

// 分类数据
const tableData = ref([])
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)

// 表单数据
const form = ref({
  id: null,
  name: "",
  sort: 0
})

const editForm = ref({
  id: null,
  name: "",
  sort: 0
})

// 删除相关
const deleteCategoryId = ref(null)
const deleteCategoryName = ref(null)

// 搜索参数
const searchForm = ref({
  name: "",
  pageNo: 1,
  pageSize: 10
})

// 获取分类列表
const getCategories = async () => {
  try {
    loading.value = true
    const response = await getPageCategories(searchForm.value)
    if (response.data && response.data.results) {
      tableData.value = response.data.results
      total.value = response.data.total
    } else if (response.data && Array.isArray(response.data)) {
      // 如果后端直接返回数组
      tableData.value = response.data
      total.value = response.data.length
    } else {
      ElMessage.error('返回的数据结构不正确')
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  getCategories()
})

// 分页处理
const handleSizeChange = (val) => {
  searchForm.value.pageSize = val
  searchForm.value.pageNo = 1
  currentPage.value = 1
  getCategories()
}

const handleCurrentChange = (val) => {
  searchForm.value.pageNo = val
  currentPage.value = val
  getCategories()
}

// 搜索
const onSubmit = () => {
  searchForm.value.pageNo = 1
  currentPage.value = 1
  getCategories()
}

// 重置搜索
const onSubmitEmpty = () => {
  searchForm.value.name = ""
  searchForm.value.pageNo = 1
  currentPage.value = 1
  getCategories()
}

// 清空表单
const clearForm = () => {
  form.value = {
    id: null,
    name: "",
    sort: 0
  }
}

// 新增分类
const addCategoryAction = () => {
  clearForm()
  addDialogVisible.value = true
}

const saveCategoryData = async () => {
  try {
    // 数据验证
    if (!form.value.name || !form.value.name.trim()) {
      ElMessage.error('请输入分类名称')
      return
    }
    
    // 确保数据格式正确
    const submitData = {
      id: form.value.id || null,
      name: form.value.name.trim(),
      sortOrder: form.value.sort || 0
    }
    await addCategory(submitData)
    ElMessage.success("新增分类成功")
    addDialogVisible.value = false
    getCategories()
  } catch (error) {
    ElMessage.error("新增分类失败")
    console.error(error)
  }
}

// 编辑分类
const editCategory = (row) => {
  editForm.value = {
    id: row.id,
    name: row.name,
    sort: row.sortOrder || 0
  }
  editDialogVisible.value = true
}

const updateCategoryData = async () => {
  try {
    // 数据验证
    if (!editForm.value.name || !editForm.value.name.trim()) {
      ElMessage.error('请输入分类名称')
      return
    }
    
    // 确保数据格式正确
    const submitData = {
      id: editForm.value.id,
      name: editForm.value.name.trim(),
      sortOrder: editForm.value.sort || 0
    }
    await updateCategory(submitData)
    ElMessage.success("更新分类成功")
    editDialogVisible.value = false
    getCategories()
  } catch (error) {
    ElMessage.error("更新分类失败")
    console.error(error)
  }
}

// 删除分类
const removeCategory = (row) => {
  deleteCategoryId.value = row.id
  deleteCategoryName.value = row.name
  deleteDialogVisible.value = true
}

const confirmDelete = async () => {
  try {
    await deleteCategory(deleteCategoryId.value)
    ElMessage.success("删除分类成功")
    deleteDialogVisible.value = false
    getCategories()
  } catch (error) {
    ElMessage.error("删除分类失败")
    console.error(error)
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN')
}
</script>

<template>
  <div class="category-management-container">
    <!-- 分类列表 -->
    <el-card>
      <div class="card-header">
        <span>分类管理</span>
        <div class="header-buttons">
          <el-button @click="$router.push('/admin')" style="margin-right: 10px;">
            返回管理后台
          </el-button>
          <el-button type="primary" @click="addCategoryAction">
            新增分类
            <el-icon class="el-icon--right">
              <Plus/>
            </el-icon>
          </el-button>
        </div>
      </div>
      <el-divider/>

      <!-- 搜索表单 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input
              v-model="searchForm.name"
              style="width: 250px"
              placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="onSubmitEmpty">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 分类表格 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          style="width: 100%"
          v-loading="loading"
          border
          stripe
        >
          <el-table-column prop="id" label="ID" width="80" align="center" fixed="left"/>
          <el-table-column prop="name" label="分类名称" min-width="200" show-overflow-tooltip/>
          <el-table-column prop="sortOrder" label="排序" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="row.sortOrder === 0 ? 'info' : 'primary'" size="small">
                {{ row.sortOrder }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" plain size="small" @click="editCategory(row)">
                <el-icon>
                  <Edit/>
                </el-icon>
                编辑
              </el-button>
              <el-button type="danger" plain size="small" @click="removeCategory(row)">
                <el-icon>
                  <Delete/>
                </el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="demo-pagination-block">
        <el-pagination
            class="el-p"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20, 25]"
            layout="jumper, total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增分类弹窗 -->
    <el-dialog
        v-model="addDialogVisible"
        title="新增分类"
        width="500px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="分类名称" required>
          <el-input v-model="form.name" placeholder="请输入分类名称"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" placeholder="请输入排序值" style="width: 100%;"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCategoryData">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑分类弹窗 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑分类"
        width="500px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="分类名称" required>
          <el-input v-model="editForm.name" placeholder="请输入分类名称"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editForm.sort" :min="0" placeholder="请输入排序值" style="width: 100%;"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateCategoryData">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
        v-model="deleteDialogVisible"
        :title="`您确认要删除分类「${deleteCategoryName}」吗？`"
        width="500px"
    >
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.category-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.table-container {
  margin: 20px 0;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  font-size: 14px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-table th) {
  background-color: #f8f9fa !important;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
  font-size: 14px;
  border-bottom: 2px solid #e9ecef;
}

:deep(.el-table td) {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table--border) {
  border: 1px solid #e9ecef;
}

:deep(.el-table .cell) {
  padding: 0 12px;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafbfc;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

/* 按钮组样式优化 */
:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 12px;
  padding: 4px 12px;
  font-weight: 500;
}

/* 表格容器样式 */
.demo-pagination-block {
  margin-top: 24px;
  padding: 16px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 搜索表单样式优化 */
.demo-form-inline {
  margin-bottom: 24px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 卡片样式优化 */
:deep(.el-card) {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: none;
}

:deep(.el-card__body) {
  padding: 24px;
}

/* 分页器样式 */
.el-p {
  margin-top: 0;
  display: flex;
  justify-content: center;
  padding: 0 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-management-container {
    padding: 10px;
  }
  
  .demo-form-inline {
    padding: 15px;
  }
  
  :deep(.el-card__body) {
    padding: 16px;
  }
  
  .table-container {
    margin: 15px 0;
  }
}
</style> 